{% extends "base/base.html" %}
{% load staticfiles %}

{% block customizedCSS %}
<!-- this page specific styles -->
    <link rel="stylesheet" type="text/css" href="/static/css/code-editor.css" />
    <link rel="stylesheet" type="text/css" href="/static/css/select2.min.css">
    <link rel="stylesheet" type="text/css" href="/static/css/lib/bootstrap.datepicker.css">
    <link rel="stylesheet" type="text/css" href="/static/css/jquery.dialogbox.css">
    <style type="text/css">
        *{font-family:'Microsoft YaHei';}
        #fm label{ margin-top: 6px; }
        #fm div{ margin-top: 15px; }
        #fm div div{ margin-top: 0 }
        #error_div{color:red}
        #error_div ul{list-style: circle;}
        #error_div ul li{text-align: left;}
        #ul_addline li{ line-height: 40px; }
        #tbody tr td a{margin-left: 10px;}
    </style>
{% endblock %}

{% block content %}
<div class="container-fluid">
            <div id="pad-wrapper">
                <div class="row-fluid editor-header">
                    <div class="span12">
                        <h4>创建销售订单</h4>
                    </div>
                </div>
                <div class="row-fluid">
                    <div class="span12" style="padding-top: 20px; border-top:1px solid #696d73;">
                       <form id="fm">
                           <div class="field-box span12" style="margin-left: 0">
                                <div class="span4">
                                    <span>销售客户：</span>
                                    <select id="se-cust" class="col-sm-3" style="z-index: 99999">
                                        <option></option>
                                    </select>
                                </div>
                                <div class="span4">
                                    <span>联系电话：</span>
                                    <input class="inline-input" type="text" id="so_phone" style="margin-bottom:0px;"/>
                                </div>
                                <div class="span4">
                                    <span>订单日期：</span>
                                    <input type="text" class="inline-input input-large datepicker col-sm-3"
                                        id="order-date" style="width:210px;margin-bottom: 0"/>
                                </div>
                            </div>
                            <div class="field-box span12" style="margin-left: 0">
                                <span>联系地址：</span>
                                <input class="inline-input span11" type="text" id="so_address" placeholder="请填写收货人地址"/>
                            </div>
                            <div class="field-box span12" style="margin-left: 0;margin-top: 30px;">
                                <a class="btn-flat primary" data-toggle="modal" data-target=".bs-example-modal-sm" id="btn-addline">
                                <i class="icon-plus"></i>添加销售项</a>
                                <a class="btn-flat info" data-toggle="modal" data-target="#info-modal" id="btn-so-note">
                                <i class="icon-book"></i>订单备注</a>
                                <a href="javascipt:void(0);" id="post_data" class="btn-glow success">
                                <i class="icon-ok"></i>保存订单</a>
                               </div>
                           <div class="field-box span12" style="margin-left: 0">
                                <table class="table table-hover">
                                    <thead>
                                <tr>
                                    <th class="span2">
                                        编号
                                    </th>
                                    <th class="span3">
                                        产品
                                    </th>
                                    <th class="span3">
                                        <span class="line"></span>
                                        单价
                                    </th>
                                    <th class="span3">
                                        <span class="line"></span>
                                        数量
                                    </th>
                                    <th class="span3">
                                        <span class="line"></span>
                                        金额
                                    </th>
                                    <th class="span3">
                                        <span class="line"></span>
                                        操作
                                    </th>
                                </tr>
                            </thead>
                            <tbody id="tbody">
                                <!-- row -->

                            </tbody>
                                </table>
                                <hr>
                                <div style="text-align: right;">
                                    <p><h5>商品数量：<em id="total_quantity">0</em>  件</h5></p>
                                    <p><h5>交易总额：<em id="total_price">0</em>  元</h5></p>
                                </div>
                           </div>
                       </form>
                    </div>
                </div>
            </div>
        </div>
         <!--modal-->
    <div class="modal fade bs-example-modal-sm" role="dialog" aria-labelledby="mySmallModalLabel" id="modal_add_line" tabindex="-2" aria-hidden="true" style="display:none;">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close close_modal1" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">添加销售行</h4>
                </div>
                <div class="modal-body">
                    <span id="line_top_error" class="alert-msg" style="color:red; padding-left:30px;"></span>
                    <ul id="ul_addline" style="list-style: none;">
                        <li id="li-product">
                            <span>产品：</span>
                            <select class="js-example-basic-single" id='se-prod'>
                                <option></option></select>
                        </li>
                        <li>
                            <span>价格：</span>
                            <input class="inline-input" type="text" id="line-price"/>
                        </li>
                        <li>
                            <span>数量：</span>
                            <input class="inline-input" type="text" id="line-quantity"/>
                        </li>
                        <li><span id="help-quantity"></span></li>
                    </ul>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default close_modal1" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="btn-Addline">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!--信息提示模态框-->
    <div class="modal fade" id="info-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display:none;">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">订单备注</h4>
          </div>
          <div class="modal-body">
            <textarea style="height: 200px;width: 510px;max-width: 510px;max-height: 200px;"
            id="so-note" placeholder="请输入订单备注信息..."></textarea>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
            <button type="button" class="btn btn-primary" id="btn-so-notes-ok">保 存</button>
          </div>
        </div>
      </div>
    </div>
    <!--end modal-->
{% endblock %}

{% block customizedJS %}
<script src="/static/js/select2.js"></script>
    <script src="/static/js/bootstrap-datepicker.js"></script>
    <script src="/static/js/jquery.dialogBox.js"></script>
    <script type="text/javascript">
            $(document).ready(function(){
                //日期控件加载
                $('#order-date').datepicker({
                    autoclose: true,
                    todayHighlight:true
                }).val(Get_today());

                //$('#info-modal,#modal_add_line').modal('hide');
                //$('#info-modal,#modal_add_line').modal('toggle');
                Array.prototype.remove = function(from, to) {
                    var rest = this.slice((to || from) + 1 || this.length);
                    this.length = from < 0 ? this.length + from : from;
                    return this.push.apply(this, rest);
                };

                var customer_cache=new Array();
                var product_cache=new Array();//商品数据缓存
                var _order=new Object();//订单对象
                var _order_line=new Array();//销售行对象
                var line_info=new Object(); //选中的商品信息


                //获取商品列表(由于重新设计,单独放出来加载)
                Get_list("product");
                Get_list("customer");

                $("#ul_addline li input[type=text]").focus(function(){
                    $("#line_top_error").html("");
                });

                //客户下拉列表数据加载
                $("#se-cust").select2({
                    placeholder:"请选择客户"
                });

                //客户下拉列表选中事件
                $("#se-cust").change(function(){
                    _order.cust=$(this).val();
                    for(var i=0; i<customer_cache.length; i++){
                        if(customer_cache[i].name==$(this).val()){
                            $("#so_phone").val(customer_cache[i].phone);
                            $("#so_address").val(customer_cache[i].address);
                        }
                    }
                });

                //商品下拉列表数据加载(点击添加销售行时触发事件)
                $("#btn-addline").click(function(){
                    //获取数据
                    var data_prods=new Array();
                    for(var i=0; i<product_cache.length; i++){
                        data_prods.push(new Object(text=product_cache[i].name));
                    }
                    //绑定数据
                    $("#se-prod").select2({
                        placeholder: "请选择商品",
                        data:data_prods
                    });
                });

                //商品下拉列表选定商品时触发事件
                $("#se-prod").change(function(){
                    var item=$(this).val();
                    for(var i=0; i<product_cache.length; i++){
                        if(product_cache[i].name==item){
                            $("#line-price").val(product_cache[i].price);
                            $("#help-quantity").html(" 库存 <strong>"+product_cache[i].inventory+"</strong> 件, 建议售价为 <b>"
                                +product_cache[i].price+ "</b> 元");
                            //传值
                            line_info.name=product_cache[i].name;
                            line_info.price=product_cache[i].price;
                            line_info.quantity=product_cache[i].quantity;
                        }
                    }
                });

                var idx=0; //标识符
                //确认添加销售行的点击事件
                $("#btn-Addline").click(function(){
                    line_info.price=$("#line-price").val();
                    line_info.quantity=$("#line-quantity").val();
                    if(Check_line(line_info)){
                        idx++;                              //标识符
                        var temp={
                            id:idx,name:line_info.name,
                            quantity:line_info.quantity,price:line_info.price
                        };
                        UI_appendline(line_info,idx);       //在table中添加销售行
                        _order_line.push(temp);             //向销售行数组中添加该销售行
                        $('#modal_add_line').modal('hide')  //关闭模态框
                        Reset_modal();                      //重置模态框
                        Set_total("add",line_info);         //设置总数量和总价钱
                    }
                })

                //取消添加销售行的时候清空modal框中的数据
                $(".close_modal1").click(function(){
                    Reset_modal();
                });


                //添加订单备注
                $("#btn-so-notes-ok").click(function(){
                    _order.note = $("#so-note").val();
                    $('#info-modal').modal('hide')
                });


                //删除订单
                $("#tbody").on('click','.line-delete',function(){
                    var id=$(this).eq(0).attr('id').toString().substring(4);
                    for(var i=0;i<_order_line.length;i++){
                        if(_order_line[i].id==id){
                             Set_total("delete",_order_line[i]);
                            _order_line.remove(i);
                        }
                    }
                    $("#tr"+id).remove();
                });


                $("#post_data").click(function(){
                    _order.date=$("#order-date").val();
                    _order.phone=$("#so_phone").val();
                    _order.address=$("#so_address").val();
                    if(_order.cust == "" || _order.cust == undefined){
                        alert("请选择客户！")
                        return false;
                    }
                    //循环遍历orderlines，然后将其转化为json格式
                    var str="";
                    for(var i=0;i<_order_line.length;i++){
                        str+='{"name":"'+_order_line[i].name+
                            '","price":'+_order_line[i].price+
                            ',"quantity":'+_order_line[i].quantity+'}'
                        if(i!=_order_line.length-1){
                            str+=",";
                        }
                    }
                    var data='{"cust":"'+_order.cust+'","date":"'+_order.date+'",'+
                        '"phone":"'+_order.phone+'","address":"'+_order.address+'",'+
                        '"note":"'+_order.note+'","orderlines":['+str+']}';
                    $.ajax({
                        type:'post',
                        data:data,
                        dataType:'json',
                        url:'/so/api_add_so/',
                        success:function(data){
                            $('#msg-dialog').dialogBox({
                                width:200,
                                hasClose: true,
                                hasBtn: true,
                                hasMask: true,
                                confirmValue: '确定',
                                confirm: function(){
                                    window.location.reload();
                                },
                                title: '信息',
                                content: '已成功添加销售订单'
                            });
                        },
                        error:function(error){
                            alert("!2");
                        }
                    });
                });


                //ajax获取数据
                function Get_list(params){
                    var array=new Array(); //缓存数据
                    var url="";
                    var name="";
                    if(params=="product"){
                        url="/product/api_prods/";
                    }else{
                        url="/customer/api_custs/";
                    }

                    $.get(
                        url,
                        function(data){
                            for(var i=0;i<data.length;i++){
                                array.push(new Object(text=data[i].name));
                            }
                            //判定是否为商品数据加载，缓存商品列表
                            if(params=="product"){
                                product_cache = data;
                            }else{
                                customer_cache=data;
                                for(var i=0;i<data.length;i++){
                                    $("#se-cust").append("<option>"+data[i].name+"</option");
                                }
                            }
                        },
                        "json"
                    );
                    return array;//返回数组
                };

                //添加销售行的验证方法
                function Check_line(info){
                    var error_info = $("#line_top_error");
                    //1.首先必须都有数据
                    if(info.name==""||info.price==""||info.quantity==""){
                        error_info.html("<i class='icon-remove-sign'></i> 请输入完整的销售行信息！");
                        return false;
                    }

                    //2.正则验证数据是否符合规范
                    //..验证价格
                    if((/^\d+\.{0,1}\d{0,2}$/).test(info.price)==false){
                        error_info.html("<i class='icon-remove-sign'></i> 价格应为整数或者小数！");
                        return false;
                    }
                    //..验证数量
                    if((/^\d+\.{0,1}\d{0,2}$/).test(info.quantity)==false){
                        error_info.html("<i class='icon-remove-sign'></i> 数量应为整数或者小数！");
                        return false;
                    }
                    if(info.quantity==0){
                        error_info.html("<i class='icon-remove-sign'></i> 销售行的数量不能为 0！");
                        return false;
                    }

                    //3.验证数量是否小于库存值
                    for(var i=0;i<product_cache.length;i++){
                        if(product_cache[i].name==info.name){
                            if(product_cache[i].inventory >= info.quantity){
                                //如果输入的数量小于库存，表示成功添加，缓存应减去数量
                                product_cache[i].inventory= product_cache[i].inventory - info.quantity;
                            }else{
                                error_info.html(
                                    "<i class='icon-remove-sign'></i> 数量错误，超过库存值！");
                                return false;
                            }
                        }
                    }
                    return true;
                }

                //向table中添加销售行(UI效果)
                function UI_appendline(info,idx){
                    var tb=$("#tbody");
                    tb.append("<tr id='tr"+idx+"'>"+
                        "<td><a href=''>#"+idx+"</a></td>"+
                        "<td><a href=''>"+info.name+"</a></td>"+
                        "<td>￥"+info.price+"</td>"+
                        "<td>"+info.quantity+"</td>"+
                        "<td>￥"+(info.quantity*info.price)+"</td>"+
                        "<td>"+
                            "<a href='#' class='line-edit' id='line"+idx+")'>编辑</a>" +
                            "<a href='#' class='line-delete' id='line"+idx+"'>删除</a>"+
                        "</td>"+
                    "</tr>");
                }

                //修改总金额和总数量
                function Set_total(method,obj){
                    var total_price=$("#total_price").html();
                    var total_quantity=$("#total_quantity").html();
                    if(method=="add"){
                        total_price=parseInt(total_price)+parseInt(obj.price)*parseInt(obj.quantity)
                        total_quantity=parseInt(total_quantity)+parseInt(obj.quantity);
                    }else{
                        total_price=parseInt(total_price)-parseInt(obj.price)*parseInt(obj.quantity)
                        total_quantity=parseInt(total_quantity)-parseInt(obj.quantity);
                    }
                    $("#total_price").html(total_price);
                    $('#total_quantity').html(total_quantity);
                }

                //清空modal框所有输入数据
                function Reset_modal(){
                    $("#line_top_error").html("");  //清除错误
                    $("#line-price").val("");   //清除加个
                    $("#line-quantity").val("");   //清除数量
                    $("#help-quantity").html("");    //清楚帮助信息
                }

                function Get_today(){
                    var today=new Date();
                    var month=today.getMonth()+1;
                    var date=today.getDate();
                    if(parseInt(month)<10){
                        month="0"+month;
                    }
                    if(parseInt(date)<10){
                        date="0"+date;
                    }
                    return today.getFullYear()+"-"+month+"-"+date;
                }

                //定义一个显示信息的Modal
                function AlertMessage(){

                }
            //Jquery结束
            });
    </script>
{% endblock %}
